package com.cinco.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
import com.cinco.server.mapper.AdminRoleMapper;
import com.cinco.server.mapper.RoleMapper;
import com.cinco.server.pojo.Admin;
import com.cinco.server.mapper.AdminMapper;
import com.cinco.server.pojo.AdminRole;
import com.cinco.server.pojo.Result;
import com.cinco.server.pojo.Role;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cinco.server.service.IAdminService;
import com.cinco.server.utils.AdminUtils;
import com.cinco.server.utils.JwtTokenUtil;
import org.springframework.security.core.Authentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cinco
 * @since 2022-01-11
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private AdminRoleMapper adminRoleMapper;

    /**
     * 登陆后返回token
     * @param username
     * @param password
     * @param code
     * @param request
     * @return
     */
    @Override
    public Result login(String username, String password, String code, HttpServletRequest request) {
        String captcha = (String) request.getSession().getAttribute("captcha");
        if (StringUtils.isEmpty(code) || !captcha.equalsIgnoreCase(code)){
            return Result.error("验证码输入错误，请重新输入");
        }
        //登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if(null == userDetails || !passwordEncoder.matches(password,userDetails.getPassword())){
            return Result.error("用户名或密码不正确");
        }
        if (!userDetails.isEnabled()){
            return Result.error("账户被冻结，请联系管理员");
        }

        //更新security登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        HashMap<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHead",tokenHead);
        return Result.success("登录成功",tokenMap);
    }

    /**
     * 根据用户名获取用户
     * @param username
     * @return
     */
    @Override
    public Admin getAdminByUserName(String username) {
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username",username).eq("enabled",true));
    }

    /**
     * 根据用户id查询角色列表
     * @param adminId
     * @return
     */
    @Override
    public List<Role> getRoles(Integer adminId) {
        return roleMapper.getRoles(adminId);
    }

    /**
     * 获取所有操作员
     * @param keywords
     * @return
     */
    @Override
    public List<Admin> getAllAdmins(String keywords) {
        return baseMapper.getAllAdmins(AdminUtils.getCurrentAdmin().getId(),keywords);
    }

    /**
     * 更新操作员角色
     * @param adminId
     * @param rids
     * @return
     */
    @Override
    @Transactional
    public Result updateAdminRole(Integer adminId, Integer[] rids) {
        adminRoleMapper.delete(new QueryWrapper<AdminRole>().eq("adminId",adminId));
        //rids为空直接返回成功即可
        if (ArrayUtils.isEmpty(rids)){
            return Result.success("更新成功!");
        }else{
            Integer result = adminRoleMapper.addAdminRole(adminId,rids);
            if (rids.length == result){
                return Result.success("更新成功！");
            }
        }

        return Result.error("更新失败！");
    }

    /**
     * 修改密码
     * @param oldPass
     * @param pass
     * @param adminId
     * @return
     */
    @Override
    public Result updateAdminPassword(String oldPass, String pass, Integer adminId) {
        //先拿到数据库地用户
        Admin admin = baseMapper.selectById(adminId);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        //判断旧密码输入是否正确
        if (encoder.matches(oldPass,admin.getPassword())){
            //给admin设置新密码
            admin.setPassword(encoder.encode(pass));
            int result = baseMapper.updateById(admin);
            if (result == 1){
                return Result.success("更新成功！");
            }
        }else{
            return Result.error("旧密码输入错误，更新失败！");
        }
        return Result.error("更新失败！");
    }

    /**
     * 修改头像
     * @param url
     * @param id
     * @param authentication
     * @return
     */
    @Override
    public Result updateAdminUserface(String url, Integer id, Authentication authentication) {
        Admin admin = baseMapper.selectById(id);
        admin.setUserFace(url);
        if(baseMapper.updateById(admin) == 1){
            Admin principal = (Admin) authentication.getPrincipal();
            principal.setUserFace(url);
            //及时更新Authentication
            SecurityContextHolder.getContext().setAuthentication(
                    new UsernamePasswordAuthenticationToken(
                            admin,authentication.getCredentials(),authentication.getAuthorities()));
            return Result.success("更新成功!",url);
        }
        return Result.error("更新失败!");
    }
}
